package com.theme.passport.controller.theme;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.theme.common.base.ConfigConstant;
import com.theme.common.base.JSONHandler;
import com.theme.common.base.http.HttpHandler;
import com.theme.common.mvc.exception.RRException;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.entity.theme.AppIconEntity;
import com.theme.passport.service.theme.AppIconService;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.*;



/**
 * 默认APP对应的ico列表
 *
 * @author live
 * @email 870459550@qq.com
 * @date 2020-11-27 16:45:44
 */
@RestController
@RequestMapping("theme/app-icon")
public class AppIconController {
    @Autowired
    private AppIconService appIconService;

    @GetMapping(value = "getAppBundled")
    public R getAppBundled(@RequestParam(value = "name") String name) throws Exception {

        List<NameValuePair > nameValuePairList = new ArrayList<>();
        NameValuePair nameValuePair = new NameValuePair();
        nameValuePair.setName("country");
        nameValuePair.setValue("cn");
        nameValuePairList.add(nameValuePair);

        NameValuePair nameValuePaiEntity = new NameValuePair();
        nameValuePaiEntity.setName("entity");
        nameValuePaiEntity.setValue("software");
        nameValuePairList.add(nameValuePaiEntity);

        NameValuePair nameValuePaiLimit = new NameValuePair();
        nameValuePaiLimit.setName("limit");
        nameValuePaiLimit.setValue("1");
        nameValuePairList.add(nameValuePaiLimit);

        NameValuePair nameValuePairTerm = new NameValuePair();
        nameValuePairTerm.setName("term");
        nameValuePairTerm.setValue(URLEncoder.encode(name, "UTF-8"));
        nameValuePairList.add(nameValuePairTerm);
        String url = "https://itunes.apple.com/search";
        String result = HttpHandler.httpGet(url,nameValuePairList);

        JsonObject jsonObject = JSONHandler.getObjectByJsonStr(result,JsonObject.class);
        int resultCount = jsonObject.get("resultCount").getAsInt();
        if (resultCount != 1){
            return R.error("从苹果网站获取app图标Icon标识错误!!!");
        }
        JsonArray jsonArray = (JsonArray) jsonObject.get("results");
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject asJsonObject = jsonArray.get(i).getAsJsonObject();
            String bundleId = asJsonObject.get("bundleId").getAsString();
            String thumb = asJsonObject.get("artworkUrl60").getAsString();

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("bundleId",bundleId);
            resultMap.put("thumb",thumb);
            return R.ok(resultMap);
        }
        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("theme:app-icon:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = appIconService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("theme:app-icon:info")
    public R info(@PathVariable("id") Long id){
		AppIconEntity appIcon = appIconService.getById(id);

        return R.ok().put("appIcon", appIcon);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("theme:app-icon:save")
    public R save(@RequestBody AppIconEntity appIcon) throws Exception {
        String name = appIcon.getName();
        if (name == null){
            return R.error("App名称不能为空!!!");
        }
        //判断name是否已经存在：
        QueryWrapper<AppIconEntity> orderWrapper = new QueryWrapper<>();
        orderWrapper.and(wrapper -> wrapper.eq("name", name));
        List<AppIconEntity> list = appIconService.list(orderWrapper);
        if (list != null && list.size() > 0){
            return R.error("该App名称已经存在!!!");
        }
        String bundleId1 = appIcon.getBundleId();
        if (bundleId1 == null) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            NameValuePair nameValuePair = new NameValuePair();
            nameValuePair.setName("country");
            nameValuePair.setValue("cn");
            nameValuePairList.add(nameValuePair);

            NameValuePair nameValuePaiEntity = new NameValuePair();
            nameValuePaiEntity.setName("entity");
            nameValuePaiEntity.setValue("software");
            nameValuePairList.add(nameValuePaiEntity);

            NameValuePair nameValuePaiLimit = new NameValuePair();
            nameValuePaiLimit.setName("limit");
            nameValuePaiLimit.setValue("1");
            nameValuePairList.add(nameValuePaiLimit);

            NameValuePair nameValuePairTerm = new NameValuePair();
            nameValuePairTerm.setName("term");
            nameValuePairTerm.setValue(URLEncoder.encode(name, "UTF-8"));
            nameValuePairList.add(nameValuePairTerm);
            String url = "https://itunes.apple.com/search";
            String result = HttpHandler.httpGet(url,nameValuePairList);

            JsonObject jsonObject = JSONHandler.getObjectByJsonStr(result,JsonObject.class);
            int resultCount = jsonObject.get("resultCount").getAsInt();
            if (resultCount != 1){
                return R.error("从苹果网站获取app图标Icon标识错误!!!");
            }
            JsonArray jsonArray = (JsonArray) jsonObject.get("results");
            JsonObject asJsonObject = jsonArray.get(0).getAsJsonObject();
            String bundleId = asJsonObject.get("bundleId").getAsString();
            String thumb = asJsonObject.get("artworkUrl60").getAsString();
            String bundleIdUrl = bundleId + "://";
            appIcon.setUrl(bundleIdUrl);
            appIcon.setBundleId(bundleId);
            appIcon.setThumb(thumb);
        }
        appIcon.setCreated(new Date());
		appIconService.save(appIcon);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("theme:app-icon:update")
    public R update(@RequestBody AppIconEntity appIcon) throws Exception{
        String name = appIcon.getName();
        if (name == null){
            return R.error("App名称不能为空!!!");
        }
		appIconService.updateById(appIcon);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("theme:app-icon:delete")
    public R delete(@RequestBody Long[] ids){
		appIconService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 上传图片文件
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExpandName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!ConfigConstant.filePattern.matcher(fileExpandName.toUpperCase()).find()) {
            return R.error("文件格式不支持");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build(null).uploadSuffix(file.getBytes(), suffix);

        return R.ok().put("filePath", url);
    }

}
